package com.cpi.cornpp.grinddistribution.service;

import java.util.ArrayList;
import java.util.Iterator;
import java.util.List;

import com.cpi.cornpp.common.exception.CornPPException;
import com.cpi.cornpp.grinddistribution.converter.GrindDistributionConverter;
import com.cpi.cornpp.grinddistribution.dao.GrindDistributionDAO;
import com.cpi.cornpp.grinddistribution.exception.GrindDistributionException;
import com.cpi.cornpp.grinddistribution.view.GrindDistributionView;

/**
 * Grind Distribution Service
 * @author Edgar Joao
 *
 */
public class GrindDistributionService {
	/**
	 * Get Grind Distribution List by Version Id
	 * @param versionId
	 * @return
	 * @throws GrindDistributionException
	 */
	public List getGrindDistribution(int versionId) throws GrindDistributionException{
		List list = null;
		GrindDistributionDAO dao = null;
		GrindDistributionConverter grindDistributionConverter = null;
		try{
			list = new ArrayList(0);
			dao = new GrindDistributionDAO();
			grindDistributionConverter = new GrindDistributionConverter();
			list.addAll(grindDistributionConverter.convertListDTOsToViews(dao.getGrindDistributionList(versionId)));
		} catch (GrindDistributionException grindDistributionException) {
			throw grindDistributionException;
		} catch (Exception e){
			GrindDistributionException grindDistributionException = null;
			e.printStackTrace(System.out);
			grindDistributionException = new GrindDistributionException(e , CornPPException.LAYER_SERVICE,CornPPException.ACTION_INSERT);
			throw grindDistributionException;
		}
		return list;
	}
	/**
	 * Save Grind Distribution
	 * @param list
	 * @throws GrindDistributionException
	 */
	public void save(List listGrindDistributionList) throws GrindDistributionException{
		Iterator iterator = null;
		GrindDistributionView view = null;
		GrindDistributionConverter converter = null;
		GrindDistributionDAO dao = null;
		try{
			dao = new GrindDistributionDAO();
			converter = new GrindDistributionConverter();
			iterator = listGrindDistributionList.iterator();
			while (iterator.hasNext()) {
				view = (GrindDistributionView) iterator.next();
				if(dao.existGrindDistribution(converter.convertViewsToDTOs(view))){
					dao.updateGrindDistribution(converter.convertViewsToDTOs(view));
				}else{
					dao.insertGrindDistribution(converter.convertViewsToDTOs(view));
				}				
			}			
		} catch (GrindDistributionException grindDistributionException) {
			throw grindDistributionException;
		} catch (Exception e){
			GrindDistributionException grindDistributionException = null;
			e.printStackTrace(System.out);
			grindDistributionException = new GrindDistributionException(e , CornPPException.LAYER_SERVICE,CornPPException.ACTION_INSERT);
			throw grindDistributionException;
		}		
	}
}
